package com.yuxi.common.html;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import com.yuxi.common.FileConfig;
import com.yuxi.common.FileUtil;
import com.yuxi.common.SkList;
import com.yuxi.common.StringUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * 生成静态页面
 *
 * @author sunke
 * @version 1.0
 * @date 2021-07-19 10:18
 */


@Component
public class SkCreateHtmlUtil {


    private final ScheduledExecutorService scheduledThreadPool;
    @Autowired
    private SpringTemplateEngine templateEngine;

    @Autowired
    private FileConfig fileConfig;


    {
        scheduledThreadPool = new ScheduledThreadPoolExecutor(10);
    }


    public void createHtml(Context context, String template, String outHtml, String lang) throws IOException {

        createHtmlList(context, template, SkList.getInstance().addObjToList(outHtml), lang);
    }

    public void createHtmlList(Context context, String template, List<String> outHtmls, String lang) throws IOException {

        if (StringUtil.isNullOrEmpty(template)) {
            return;
        }
        if (template.lastIndexOf(".html") == -1) {
            template = template + ".html";
        }


        if (StringUtil.isObjEmpty(outHtmls)) {
            outHtmls = SkList.getInstance().addObjToList(template);
        }

        for (String outHtml : outHtmls) {
            String finalOutHtml = outHtml;

            //  String sourceHtmlPath = htmlPath + File.separator + source;
            String finalTemplate = template;
            scheduledThreadPool.execute(() -> {
                try {
                    int index = finalOutHtml.lastIndexOf("/");
                    if (index >= 0) {
                        FileUtil.mkdirs(fileConfig.getHtmlPath() + File.separator + finalOutHtml.substring(0, index));
                    } else {
                        FileUtil.mkdirs(fileConfig.getHtmlPath());
                    }

                    FileWriter write = new FileWriter(fileConfig.getHtmlPath() + File.separator + finalOutHtml + ".html");
                    templateEngine.process(finalTemplate, context, write);
                } catch (IOException e) {
                    e.printStackTrace();

                }
            });
        }


    }


}
